package com.axonactive.yolo.monitor;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.axonactive.yolo.domain.UserEmail;
import com.axonactive.yolo.exception.UserEmailNotFoundException;
import com.axonactive.yolo.exception.UserNotFoundException;
import com.axonactive.yolo.service.interfaces.UserEmailService;
import com.axonactive.yolo.service.interfaces.UserService;
import com.axonactive.yolo.util.CONSTANTS;

public class UnactivatedEmailCleaner {

	@Autowired
	private UserEmailService userEmailService;

	@Autowired
	private UserService userService;

	private final static Logger LOGGER = Logger.getLogger(UnactivatedEmailCleaner.class);

	public boolean run() throws UserEmailNotFoundException, UserNotFoundException {
		LOGGER.info("UnactivatedEmailCleaner IN");
		List<UserEmail> unactivatedUserEmail = getUnactivedEmail();
		LOGGER.info(unactivatedUserEmail.size() + " unactivated email(s) found");

		for (int i = 0; i < unactivatedUserEmail.size(); i++) {
			long currentTime = new Date().getTime() / 1000L;
			LOGGER.info("Current time: " + currentTime);

			long registrationTime = Long.parseLong(unactivatedUserEmail.get(i).getRegistrationDate());
			LOGGER.info("[" + unactivatedUserEmail.get(i).getEmail() + "].registrationTime: " + registrationTime);

			long difference = currentTime - registrationTime;
			LOGGER.info("Difference: " + difference);

			if (difference > CONSTANTS.UNACTIVATED_EMAIL_LIFECYCLE) {
				int userEmailId = unactivatedUserEmail.get(i).getId();
				deleteUserEmail(userEmailId);

				// user has 0 email now
				int userId = unactivatedUserEmail.get(i).getIdUser();
				int numberOfEmailByUser = userEmailService.findAllEmailByUserId(userId).size();
				LOGGER.info("UserId [" + userId + "] has " + numberOfEmailByUser + " email(s)");

				if (numberOfEmailByUser == 0) {
					deleteUser(userId);
				}
			}
		}
		LOGGER.info("UnactivatedEmailCleaner OUT");
		return true;
	}

	private List<UserEmail> getUnactivedEmail() {
		return userEmailService.getUnactivedEmail();
	}

	private void deleteUserEmail(int userEmailId) throws UserEmailNotFoundException {
		LOGGER.info("UserEmail [" + userEmailService.findById(userEmailId).getEmail() + "] has been deleted");
		userEmailService.delete(userEmailId);
	}

	private void deleteUser(int userId) throws UserNotFoundException {
		LOGGER.info("User [" + userService.findById(userId).getId() + "] has been deleted");
		userService.delete(userId);
	}

	public void injectService(UserEmailService userEmailService, UserService userService) {
		this.userEmailService = userEmailService;
		this.userService = userService;
	}

	// public methods for testing
	public List<UserEmail> getUnactivedEmailTest() {
		return this.getUnactivedEmail();
	}
}
